const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🔍 收到施工队伍审核请求')
  
  try {
    const { OPENID } = cloud.getWXContext()
    const { teamId, action, reason = '' } = event
    
    // 验证参数
    if (!teamId || !action) {
      return {
        success: false,
        error: '缺少必要参数'
      }
    }
    
    if (!['approve', 'reject'].includes(action)) {
      return {
        success: false,
        error: '无效的审核操作'
      }
    }
    
    // 查找要审核的队伍
    const teamResult = await db.collection('construction_teams')
      .doc(teamId)
      .get()
    
    if (!teamResult.data) {
      return {
        success: false,
        error: '未找到指定的施工队伍'
      }
    }
    
    const team = teamResult.data
    
    // 检查当前状态
    if (team.auditStatus !== 'pending') {
      return {
        success: false,
        error: `该申请已经${team.auditStatus === 'approved' ? '通过审核' : '被拒绝'}，无法重复操作`
      }
    }
    
    // 准备更新数据
    const updateData = {
      auditStatus: action === 'approve' ? 'approved' : 'rejected',
      canReceiveOrders: action === 'approve', // 只有通过审核才能接单
      auditTime: new Date(),
      auditReason: reason,
      auditBy: OPENID, // 记录审核人
      updateTime: new Date()
    }
    
    // 如果是通过审核，设置一些默认值
    if (action === 'approve') {
      updateData.status = 'available' // 设置为可接单状态
    }
    
    // 更新数据库
    await db.collection('construction_teams')
      .doc(teamId)
      .update({
        data: updateData
      })
    
    console.log(`✅ 审核完成: ${action === 'approve' ? '通过' : '拒绝'} - ${team.name}`)
    
    // 发送通知给申请人
    try {
      await sendAuditNotification(team, action, reason)
    } catch (notifyError) {
      console.warn('⚠️ 发送审核通知失败:', notifyError)
      console.warn('⚠️ 通知错误详情:', notifyError.message)
      console.warn('⚠️ 通知错误堆栈:', notifyError.stack)
    }
    
    return {
      success: true,
      message: `审核${action === 'approve' ? '通过' : '拒绝'}成功`,
      data: {
        teamId: teamId,
        teamName: team.name,
        action: action,
        auditStatus: updateData.auditStatus,
        canReceiveOrders: updateData.canReceiveOrders
      }
    }
    
  } catch (error) {
    console.error('❌ 审核操作失败:', error)
    return {
      success: false,
      error: error.message || '审核操作失败'
    }
  }
}

// 发送审核通知
async function sendAuditNotification(team, action, reason) {
  console.log('📧 发送审核结果通知')
  console.log('📋 通知参数:', {
    teamName: team.name,
    teamOpenid: team.openid,
    action: action,
    reason: reason
  })

  try {
    const isApproved = action === 'approve'
    const notificationData = {
      type: 'audit_result',
      title: `施工队伍审核${isApproved ? '通过' : '拒绝'}`,
      content: isApproved
        ? `恭喜！您的${team.typeName}"${team.name}"注册申请已通过审核，现在可以接收预约服务订单了。`
        : `很抱歉，您的${team.typeName}"${team.name}"注册申请未通过审核。您可以根据拒绝原因修改信息后重新提交申请。`,
      targetOpenid: team.openid, // 发送给申请人
      isRead: false, // 默认未读
      data: {
        teamId: team._id || team.id,
        teamName: team.name,
        teamType: team.typeName,
        action: action,
        reason: reason,
        auditTime: new Date()
      },
      createTime: new Date()
    }

    // 插入通知记录
    const notificationResult = await db.collection('user_notifications').add({
      data: notificationData
    })

    console.log('✅ 审核通知发送成功:', isApproved ? '通过通知' : '拒绝通知')
    console.log('📝 通知记录ID:', notificationResult._id)
    console.log('📧 通知内容:', notificationData)

  } catch (error) {
    console.error('❌ 发送审核通知失败:', error)
    throw error
  }
}
